package com.sq.util;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

import com.sq.util.exception.CommonException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ParallelUtil {

    /**
     * 并行处理多个任务，等待全部完成
     *
     * @param threadNamePrefix
     * @param list
     *            需要完成的任务
     * @param threadNum
     *            并行处理的线程数
     */
    public static void parallelRun(String threadNamePrefix, List<Runnable> list, int threadNum) {
        LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue();
        int num = list.size();
        final CountDownLatch doneSignal = new CountDownLatch(num);
        for (Runnable runnable : list) {
            queue.add(() -> {
                runnable.run();
                doneSignal.countDown();
            });
        }
        for (int i = 0; i < threadNum; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < num; j++) {
                    if (queue.isEmpty()) {
                        return;
                    }
                    Runnable poll = queue.poll();
                    if (poll == null) {
                        return;
                    }
                    poll.run();
                }
            });
            thread.setName(threadNamePrefix + "_" + StringUtil.getRandomString(5));
            thread.start();
        }
        try {
            doneSignal.await();
        } catch (InterruptedException e) {
            throw new CommonException(e.getMessage());
        }
    }
}
